package salary.calculation.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import salary.calculation.common.excel.object.ExportData;
import salary.calculation.common.excel.object.ExportData2;
import salary.calculation.common.excel.object.ExportData3;
import salary.calculation.common.excel.object.ImportData;
import salary.calculation.common.util.EasyExcelUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author liguirong
 * @date 2022-02-11
 */
@RestController
@Slf4j
public class CalculationController {

    @PostMapping("/")
    public void calculation(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response) {
        try {
            List<ImportData> dataList = EasyExcelUtils.read(file, ImportData.class);
            log.info("importData={}", JSON.toJSONString(dataList));
            //跟班数据
            List<ExportData> attendantList = calculateAttendant(dataList);
            //一线数据
            List<ExportData2> firstLineList = calculateFirstLine(dataList);
            //老总数据
            List<ExportData2> bossList = calculateBoss(dataList);

            String fileName = "值班金额" + LocalDate.now() + ExcelTypeEnum.XLSX.getValue();
            response.setContentType("mutipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "跟班").head(ExportData.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            excelWriter.write(attendantList, writeSheet);

            WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "一线").head(ExportData2.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            excelWriter.write(firstLineList, writeSheet2);

            WriteSheet writeSheet3 = EasyExcel.writerSheet(2, "老总").head(ExportData3.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            excelWriter.write(bossList, writeSheet3);
            excelWriter.finish();
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("", e);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().write("解析出错！赶紧找程序猿处理吧(●'◡'●)");
            } catch (IOException e2) {
                log.error("", e2);
            }
        }
    }

    private List<ExportData> calculateAttendant(List<ImportData> dataList) {
        Map<String, Integer> attendantMap = new TreeMap<>();
        //总共100元，这个单位是分
        int total = 10000;
        for (int i = 0; i < dataList.size(); i++) {
            ImportData data = dataList.get(i);
            List<String> attendantList = new ArrayList<>();
            attendantList.add(data.getAttendant1());
            attendantList.add(data.getAttendant2());
            attendantList.add(data.getAttendant3());
            attendantList.add(data.getAttendant4());
            attendantList.add(data.getAttendant5());
            attendantList.add(data.getAttendant6());
            attendantList.add(data.getAttendant7());
            attendantList.add(data.getAttendant8());
            attendantList = attendantList.stream().filter(p -> StringUtils.isNotBlank(p)).collect(Collectors.toList());
            if(!attendantList.isEmpty()) {
                //平均每个人得的钱
                int money = total / attendantList.size();
                for (String attendant : attendantList) {
                    setMoney(attendantMap, money, attendant);
                }
            }
        }
        return transferList1(attendantMap);
    }

    private List<ExportData> transferList1(Map<String, Integer> attendantMap) {
        List<ExportData> resultList = new ArrayList<>();
        int totalMoney = 0;
        for (Map.Entry<String, Integer> entry : attendantMap.entrySet()) {
            totalMoney += entry.getValue();
            ExportData exportData = new ExportData();
            exportData.setName(entry.getKey());
            exportData.setMoney(entry.getValue() / 100.0);
            resultList.add(exportData);
        }
        resultList.add(new ExportData());
        ExportData exportData = new ExportData();
        exportData.setName("总计：");
        exportData.setMoney(totalMoney / 100.0);
        resultList.add(exportData);
        return resultList;
    }

    private List<ExportData2> calculateFirstLine(List<ImportData> dataList) {
        Map<String, Integer> firstLineMap = new TreeMap<>();
        for (int i = 0; i < dataList.size(); i++) {
            ImportData data = dataList.get(i);
            if (StringUtils.isNotBlank(data.getFirstLine())) {
                String name = getName(data.getFirstLine());
                firstLineMap.put(name, firstLineMap.getOrDefault(name, 0) + 100);
            }
        }
        return transferList2(firstLineMap);
    }

    private List<ExportData2> calculateBoss(List<ImportData> dataList) {
        Map<String, Integer> firstLineMap = new TreeMap<>();
        for (int i = 0; i < dataList.size(); i++) {
            ImportData data = dataList.get(i);
            if (StringUtils.isNotBlank(data.getBoss())) {
                firstLineMap.put(data.getBoss(), firstLineMap.getOrDefault(data.getBoss(), 0) + 100);
            }
        }
        return transferList2(firstLineMap);
    }

    private List<ExportData2> transferList2(Map<String, Integer> firstLineMap) {
        List<ExportData2> resultList = new ArrayList<>();
        int totalMoney = 0;
        for (Map.Entry<String, Integer> entry : firstLineMap.entrySet()) {
            totalMoney += entry.getValue();
            ExportData2 exportData = new ExportData2();
            exportData.setName(entry.getKey());
            exportData.setMoney(entry.getValue());
            resultList.add(exportData);
        }
        resultList.add(new ExportData2());
        ExportData2 exportData = new ExportData2();
        exportData.setName("总计：");
        exportData.setMoney(totalMoney);
        resultList.add(exportData);
        return resultList;
    }

    private void setMoney(Map<String, Integer> attendantMap, int money, String attendant) {
        attendant = getName(attendant);
        int value = attendantMap.getOrDefault(attendant, 0) + money;
        //三次33.33元算100元
        if (value == 9999) {
            value = 10000;
        }
        attendantMap.put(attendant, value);
    }

    private String getName(String attendant) {
        //去掉首字母
        if (attendant.charAt(0) >= 'A' && attendant.charAt(0) <= 'z') {
            attendant = attendant.substring(1);
        }
        //去掉最后一位数字
        if (attendant.charAt(attendant.length() - 1) >= '0' && attendant.charAt(attendant.length() - 1) <= '9') {
            attendant = attendant.substring(0, attendant.length() - 1);
        }
        return attendant;
    }
}
